import { loc } from '../../local';

const side_width = 240;

const getClientH = () => document.body.clientHeight;

const getClientW = (side) => {
    const w = document.body.clientWidth
    if (side) {
        return w - side_width - 10;
    }

    return w;
};

const is_empty = (data) => {
    if (!data) {
        return true;
    }

    return data.length <= 0;
};

const cutTxt = (txt, l=4, sub=5) => {
    if (!txt) {
        return "";
    }

    const len = txt.length;
    if (len <= l) {
        return txt;
    }

    let con = txt.substring(0, sub);
    con += "...";

    let pos = len - sub;
    if (pos < sub) {
        pos = sub
    }

    con += txt.substring(pos);

    return con;
};

const obj_empty = (data) => {
    if (!data) {
        return true;
    }

    return Object.keys(data).length <= 0;
};

const obj_str = (v, k) => {
    if (obj_empty(v)) {
        return "";
    }

    const r = v[k];
    if (r) {
        return "" + r;
    }
    else {
        if (`${r}` === "false") {
            return "false";
        }

        if (!isNaN(r)) {
            return "" + r;
        }
    }

    return "";
};

const obj_bool = (v, k) => {
    if (obj_empty(v)) {
        return false;
    }

    const val = v[k];
    if (val === "true") {
        return true;
    }
    else if (val === "false") {
        return false;
    }

    if (val) {
        return val;
    }

    return false;
};

const for_obj = (obj, fn) => {
    if (!obj || !fn) {
        return;
    }

    Object.entries(obj).forEach(([k, v]) => fn(k, v));
};

const split_md = (v, d="keyd", m="keym") => {
    if (obj_empty(v)) {
        return [null, null];
    }

    let km = v[m];
    if (!km) {
        return [null, null];
    }

    let kd = v[d];
    if (!kd) {
        return [null, null];
    }

    km = km.split(",");
    kd = kd.split(",");

    return [km, kd];
};

const get_num = (v, k) => {
    if (!v) {
        return 0;
    }

    let n = parseInt(v[k], 10);
    if (isNaN(n)) {
        return 0;
    }

    return n;
};

const jsonData = (data) => {
    return {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json'
        }
    };
};

const sendJson = (url, data, okfun=null, errfun=null, fnDone=null) => {
    fetch(url, jsonData(data))
        .then(res => {
            if (res.ok) {
                return res.json();
            }

            console.log(res);

            throw new Error('err');
        })
        .then(
            r => {
                const data = r["data"];
                const code = r["code"];
                const message = r["message"];

                if (code === 1000) {
                    if (okfun) {
                        okfun(data);
                    }
                }
                else {
                    if (errfun) {
                        errfun(message);
                    }
                }

                if (fnDone) {
                    fnDone();
                }
            },
            e => {
                if (errfun) {
                    errfun(e);
                }

                if (fnDone) {
                    fnDone();
                }
            }
        )
        .catch(e => {
            console.log(`error: ${e}`);
        });
};

const no_del = (m=loc("qdsc")) => {
    if (!window.confirm(m)) {
        return true;
    }

    return false;
};

const obj_date = (v, k) => {
    if (obj_empty(v)) {
        return new Date();
    }

    if (v[k]) {
        return v[k];
    }

    return new Date();
};

const obj_str_trim = (v, k) => {
    let r = obj_str(v, k);
    return r.trim();
};

const lst_user = (ret) => {
    if (is_empty(ret)) {
        return null;
    }

    const tmp = [];
    ret.forEach(d => {
        if (d.sn === "admin") {
            return;
        }

        tmp.push({
            id: d.uid,
            sn: d.sn,
            name: d.name,
        });
    });

    return tmp;
};

const sleep_base = (ms) => new Promise(r => setTimeout(r, ms));

const sleep = (tm, hcmd) => sleep_base(tm).then(() => hcmd());

const cut_text = (v, len=4) => {
    if (!v) {
        return "";
    }

    if (v.length > len) {
        let r = v.slice(0, len);
        r += "...";
        return r;
    }

    return v;
};

const d_sort = (r, k, rev=false) => {
    if (is_empty(r)) {
        return;
    }

    if (rev) {
        r.sort((a, b) => {
            if (a[k] > b[k]) {
                return -1;
            }

            if (a[k] < b[k]) {
                return 1;
            }

            return 0;
        });

        return;
    }

    r.sort((a, b) => {
        if (a[k] > b[k]) {
            return 1;
        }

        if (a[k] < b[k]) {
            return -1;
        }

        return 0;
    });
};

const d_sort_num = (r, k) => {
    r.sort((a, b) => parseInt(a[k], 10) - parseInt(b[k], 10));
};

const is_obj_eq = (a, b) => {
    if (obj_empty(a) && obj_empty(b)) {
        return true;
    }

    if (obj_empty(a) && !obj_empty(b)) {
        return false;
    }

    if (obj_empty(b) && !obj_empty(a)) {
        return false;
    }

    let eq = true;

    for_obj(a, (k, v) => {
        if (!eq) {
            return;
        }

        if (b[k] === v) {
            return;
        }

        eq = false;
    });

    return eq;
};

export {d_sort, d_sort_num, getClientW, getClientH, no_del, jsonData, sendJson, get_num, split_md, obj_empty, for_obj, obj_bool,
    cut_text, is_obj_eq, sleep, lst_user, obj_str_trim, obj_date, side_width, obj_str, cutTxt, is_empty};
